const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    courseId: '',
    courseName: '',
    showMask: false,
    showPopup: false,
    courseTestResult: true, //课程测试结果
    finish: false, //课程是否测试完成
    list: [],
    courseObj: {}, //当前的题目
    courseTestIndex: 0, //当前显示的题目
    total: 0, //题目总数,
    statusHeight: 0, //状态栏高度
    navHeight: 0 //标题栏高度
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      statusHeight: app.globalData.statusHeight,
      navHeight: app.globalData.navHeight,
      courseId: options.courseId,
      courseName: options.courseName,
      status:parseInt(options.status)
    })

    this.getTest();
  },
  // 获取课程测试题目
  getTest() {
    app.fetchRequest({
      url: `/user/exam/start/${this.data.courseId}`,
      data: {},
      success: (res) => {
        if (res && res.length) {
          res.forEach(item => {
            item.isSelect = false; //是否选择了选项
            item.selectItemValue = ''; //选择了什么
          })
        }
        this.setData({
          list: res,
          courseObj: res[0],
          total: res.length
        })
      }
    })
  },
  select(e) {
    const index = e.currentTarget.dataset.index;
    this.data.courseObj.isSelect = true;

    if (this.data.courseObj.examType) {
      this.data.courseObj.selectItemValue = e.currentTarget.dataset.item;
    } else {
      this.data.courseObj.selectItemValue = this.data.courseObj.options[index].optionValue;
    }
    // 如果其中一题为错，则测试不通过
    if (this.data.courseObj.selectItemValue !== this.data.courseObj.correctOption) {
      this.setData({
        courseTestResult: false
      })
    }
    this.setData({
      courseObj: this.data.courseObj
    })

    if (this.data.total <= this.data.courseTestIndex + 1) {
      setTimeout(() => {
        this.setData({
          finish: true
        })
      }, 500)
      if (this.data.courseTestResult && !this.data.status) {
        this.isCoursePassed();
      }
      return;
    }
    setTimeout(() => {
      this.setData({
        courseTestIndex: ++this.data.courseTestIndex,
        courseObj: this.data.list[this.data.courseTestIndex]
      })
    }, 500)
  },
  isCoursePassed() {
    app.fetchRequest({
      url: `/user/exam/passed/${this.data.courseId}`,
      data: {},
      success: (res) => {}
    })
  },
  tapTestAgain() {
    this.setData({
      courseTestResult: true,
      finish: false,
      courseTestIndex: 0
    })
    this.getTest();
  },
  back() {
    this.setData({
      showMask: true,
      showPopup: true
    })
  },
  navigateBack() {
    wx.navigateBack()
  },
  hiddenMask() {
    this.setData({
      showMask: false,
      showPopup: false
    })
  }

})